package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zsk
 * @create 2022-04-09-16:36
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {


    //分页查询频道列表
    @Override
    public ResponseResult listByName(ChannelDto dto) {

        //构建分页条件
        Page<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());

        //构建查询条件
        LambdaQueryWrapper<WmChannel> wrapper = new LambdaQueryWrapper<>();
        //判断姓名不为null查询
        if (!StringUtils.isEmpty(dto.getName())){
            wrapper.like(WmChannel::getName,dto.getName());
        }

        //分页查询
        Page<WmChannel> iPage = this.page(page, wrapper);
        long total = iPage.getTotal();
        List<WmChannel> records = iPage.getRecords();

        //返回分页对象
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize()
                ,total,records);

        //返回
        return result;
    }

    //新增频道
    @Override
    public ResponseResult saveWnChannel(WmChannel entity) {

        //检查参数是否为null
        if (entity == null || StringUtils.isEmpty(entity.getName())){
            //为空返回提示
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //先查询数据库中是否存在此频道
        //构建查询条件
        LambdaQueryWrapper<WmChannel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmChannel::getName,entity.getName());

        int count = this.count(wrapper);
        if (count > 0){
            //代表已存在，返回提示
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //补全参数
        entity.setCreatedTime(new Date());

        //添加数据
        this.save(entity);

        //返回结果
        return ResponseResult.okResult();
    }
}
